<?php

namespace app\service;

use think\facade\Cache;

class CacheService
{
    public static function clear()
    {
        Cache::clear();
    }

    // 缓存删除
    public static function deleteCacheList($listKey):void
    {
        if(empty(Cache::get($listKey))){
            return;
        }
        $cacheList = json_decode(Cache::get($listKey),true);
        if(empty($cacheList)){
            return;
        }
        foreach ($cacheList as $key){
            Cache::delete($key);
        }
        Cache::delete($listKey);
    }

    // 缓存追加
    public static function append($key,$value)
    {
        $cacheData = Cache::get($key);
        if(empty($cacheData)){
            Cache::set($key,json_encode([$value]));
        }else{
            $cacheData = json_decode($cacheData,true);
            $cacheData[] = $value;
            Cache::set($key,json_encode($cacheData));
        }
    }

    /**
     * 根据模型名称删除相关缓存
     * @param $className
     * @return void
     */
    public static function deleteRelationCacheByClassName($className)
    {
        // 删除列表缓存
        $listKey = $className . '_cache_list';
        self::deleteCacheList($listKey);
        // 删除详情缓存
        $detailKey = $className . '_cache_detail';
        self::deleteCacheList($detailKey);
    }

    /**
     * 根据模型名称删除相关缓存
     * @return void
     * @throws \ReflectionException
     */
    public static function deleteRelationCacheByObject($object)
    {
        $className = ClassService::getClassName($object);
        // 删除列表缓存
        $listKey = $className . '_cache_list';
        self::deleteCacheList($listKey);
        // 删除详情缓存
        $detailKey = $className . '_cache_detail';
        self::deleteCacheList($detailKey);
    }
}
